package cn.com.wxd.service.weather;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import cn.com.wxd.common.GlobalConstant;
import cn.com.wxd.common.framedata.FrameDataUtil;


public class WeatherService
{
	private static final Logger log = LoggerFactory.getLogger(WeatherService.class);
	private static final String WEATHERSERVICEURL= "http://flash.weather.com.cn/wmaps/xml/china.xml";
	private static final String WEATHERPICPATH="/static/images/weather/";
	/**
	 * 更新天气预报
	 * @throws Exception
	 *
	 * */
	public static String upDateWheather() throws Exception {
		String result = "";
		BufferedReader read = null;
		try
		{
			URL realurl = new URL(WEATHERSERVICEURL);
			URLConnection connection = realurl.openConnection();
			connection.setReadTimeout(2000);
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

			connection.connect();

			@SuppressWarnings({ "unused", "rawtypes" })
			Map map = connection.getHeaderFields();
			read = new BufferedReader(
					new InputStreamReader(connection.getInputStream(), "UTF-8"));
			String line;
			while ((line = read.readLine()) != null)
			{
				result = result + line;
			}
			FrameDataUtil.saveFrameData(GlobalConstant.WEATHERFRAMEDATANAME, result);
			//开始填充缓存
			WeatherCache.getInstance().setWeatherData(result); //每次更新完之后刷新缓存到最新数据
			List<Weatherbean> weathers = analyXml();
			for (Weatherbean weather : weathers) {
				WeatherCache.getInstance().setWeatherCache(weather);
			}
		} catch (Exception e) {
            log.error("天气更新失败!"+e.getMessage(),e);
			throw e;
		}
		finally
		{
			if (read != null) {
				try {
					read.close();
				} catch (IOException e) {
                    log.error(e.getMessage(),e);
				}
			}
		}
		return result;
	}
	/**
	 * 解析xml文件
	 * @return
	 */
	private static  List<Weatherbean> analyXml()
	{
		String data = WeatherCache.getInstance().getWeatherData();
		if(data.trim().equals("")){
			try {
				data = FrameDataUtil.getDataByName(GlobalConstant.WEATHERFRAMEDATANAME); //如果获取到不数据，则从数据库装载数据
				if(data!=null&&!data.trim().equals("")){
					WeatherCache.getInstance().setWeatherData(data);
				}
			} catch (Exception e) {
                log.error("没有"+WEATHERSERVICEURL+"的天气信息数据!",e);
			}
		}
		SAXReader reader = new SAXReader();
		reader.setEncoding("GBK");
		List<Weatherbean> weachers = new ArrayList<Weatherbean>();
		try {
			Document document = reader.read(new ByteArrayInputStream(data.getBytes("GBK")));

			Element root = document.getRootElement();

			for (@SuppressWarnings("rawtypes")
				 Iterator iterator = root.elementIterator("city"); iterator.hasNext(); )
			{
				Element escity = (Element)iterator.next();
				Weatherbean weather = new Weatherbean();
				weather.setQuName(escity.attributeValue("quName"));
				weather.setCityName(escity.attributeValue("cityname"));
				weather.setPyName(escity.attributeValue("pyName"));
				weather.setState1(Integer.valueOf(escity.attributeValue("state1")).intValue());
				weather.setState2(Integer.valueOf(escity.attributeValue("state2")).intValue());
				weather.setStateDetailed(escity.attributeValue("stateDetailed"));
				weather.setTem1(Integer.valueOf(escity.attributeValue("tem1")).intValue());
				weather.setTem2(Integer.valueOf(escity.attributeValue("tem2")).intValue());
				weather.setWindState(escity.attributeValue("windState"));
				weachers.add(weather);
			}
			return weachers;
		}
		catch (DocumentException e)
		{
            log.error("解析出现错误"+e.getMessage(),e);
		} catch (UnsupportedEncodingException e) {
            log.error("解析出现错误"+e.getMessage(),e);
		}
		return null;
	}

	/**
	 * 获取天气信息，
	 * @param quName 省份名称
	 * @return
	 * @throws Exception
	 */
	public Weatherbean getWeather(String quName) throws Exception {
		if(quName==null||quName.equals("")){
			return null;
		}
		Weatherbean weatherbean = WeatherCache.getInstance().getWeatherCache(quName);
		if(weatherbean==null){
			for (Weatherbean wb : analyXml()) {
				if (wb.getQuName().equals(quName)) {
					weatherbean= new Weatherbean();
					weatherbean = wb;
					break;
				}
			}
			if(weatherbean!=null){
				WeatherCache.getInstance().setWeatherCache(weatherbean);  //设置缓存
			}
			return weatherbean;
		}
		if(weatherbean!=null){
			Calendar cal = Calendar.getInstance();
			int hour = cal.get(Calendar.HOUR_OF_DAY);
			String dn = "d";
			if(hour>20&&hour<8){
				dn = "n";
			}
			weatherbean.setWeatherImage(WEATHERPICPATH+dn+weatherbean.getState1()+".png"); //设置图片
		}
		return weatherbean;
	}
}